package io.gitee.kenewstar.dbmq;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import io.gitee.kenewstar.dbmq.data.DbDataHandler;
import io.gitee.kenewstar.dbmq.handler.DbMqCoreHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kenewstar
 */
public class DbMqMessageProducer extends DbMqCoreHandler {

    public DbMqMessageProducer() {}

    public DbMqMessageProducer(DbDataHandler dbDataHandler, DbMqConfigProperties dbMqConfigProperties) {
        this.dbDataHandler = dbDataHandler;
        this.dbMqConfigProperties = dbMqConfigProperties;

    }

    public int sendMessage(String topic, String messageBody) {
        List<Integer> tags = processTag(topic);
        return this.dbDataHandler.sendMessage(topic, ListUtil.of(messageBody), tags);
    }

    public int sendMessage(String topic, List<String> messageBodyList) {
        if (CollUtil.isEmpty(messageBodyList)) {
            return 0;
        }

        if (messageBodyList.size() == 1) {
            return this.sendMessage(topic, messageBodyList.get(0));
        }

        List<Integer> tags = processTag(topic);
        return this.dbDataHandler.sendMessage(topic, messageBodyList, tags);
    }

    private List<Integer> processTag(String topic) {
        final List<ConsumerRegisterInfo> topicRegister = this.dbDataHandler.pullRegisterInfo(ListUtil.of(topic));
        List<Integer> tags = new ArrayList<>(topicRegister.size());
        for (int i = 0; i < topicRegister.size(); i++) {
            if (!checkRegisterExpire(topicRegister.get(i))) {
                tags.add(i + 1);
            }
        }
        return tags;
    }




}
